// pages/rcpt/overview/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pdfUrl: 'https://mm-mb-test.oss-cn-beijing.aliyuncs.com/yj/ms/%E4%BD%99%E6%B1%9F%E7%BE%8E%E6%99%AF%E3%80%81%E4%BD%99%E6%B1%9F%E7%BE%8E%E9%A3%9F.pdf',
    jsonUsedData: null,
    contentIndex01:null
  },
  downloadPDF(){
    wx.showLoading({
      title: '下载中，请耐心等待'
    })
    wx.downloadFile({
      url: this.data.pdfUrl,
      success:(res) =>{
        if(res.statusCode === 200){

          wx.openDocument({
            filePath: res.tempFilePath,
            showMenu:true
          })
        }
      }
    })
  },

  
  processJsonData: function (menu, article, articleContent) {
    console.log(menu, "ss");
    // const menuMap = new Map();
    function buildMenuTree(menu) {

      return menu.map(menuItem => {
        console.log(menuItem.childrens, 'l')
        
          const articleInsert = article.filter(articleItem => articleItem.menuId === menuItem.id)
            .map(articleItem => {
              return {
                ...articleItem,
                content: articleContent.find(contentItem => contentItem.articlesId === articleItem.id)
              }  })
// 没有子菜单
              if (menuItem.childrens === null) {
                return {
                  ...menuItem,
                  article: articleInsert
                }
              }
            //有子菜单
          else{
            return {
              ...menuItem,
              article: articleInsert,
              childrens: buildMenuTree(menuItem.childrens)
              
            }
            }
      })
        }
  
     // 构建完整的菜单树
  const result = buildMenuTree(menu);

  console.log("outputEND", result);
  return result;
    //     const menuMap = new Map();

    //     // 创建菜单项的映射
    //     menu.forEach(menuItem => {
    //         menuMap.set(menuItem.id, {
    //             ...menuItem,
    //             articles: [],
    //             childMenu: []
    //         });
    //     });

    //     // 关联文章数据到菜单项
    //     article.forEach(articleItem => {
    //       // 如果相等
    //       // if(articleItem.menuId === menuItem.id){
    //         const contentData = articleContent.find(contentItem => contentItem.articlesId === articleItem.id);
    //         const menuItem = menuMap.get(articleItem.menuId);
    //         if (menuItem) {
    //             menuItem.articles.push({
    //                 articleId: articleItem.id,
    //                 title: articleItem.title,
    //                 sortOrder: articleItem.sortOrder,
    //                 state: articleItem.state,
    //                 type: articleItem.type,
    //                 articleContent: contentData ? contentData.content : null
    //             });
    //         }

    //     });

    //     // 调试输出
    //     console.log('MenuMap after adding articles:', menuMap);

    //     // 建立菜单树结构
    //     const rootMenu = [];
    //     menuMap.forEach(menuItem => {
    //         if (menuItem.parentId === null) {
    //             rootMenu.push(menuItem);
    //         } else {
    //             const parentMenu = menuMap.get(menuItem.parentId);
    //             if (parentMenu) {
    //                 parentMenu.childMenu.push(menuItem);
    //             }
    //         }
    //     });

    //     // 调试输出
    //     console.log('Root Menu:', rootMenu);
    //     return rootMenu;
    // }

  },


  downloadAndParseJsonFile: function (url) {
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: url,
        method: 'get',
        success: (res) => {
          if (res.statusCode === 200) {
            console.log(res);
            const filePath = res.tempFilePath
            // const fs = ;
            //read local json file
            wx.getFileSystemManager().readFile({
              filePath: filePath,
              encoding: 'utf-8',
              success: (data) => {
                //解析JSON数据
                const jsonData = JSON.parse(data.data)
                console.log('jsonData', jsonData)
                resolve(jsonData);
                // wx.setStorageSync('menu',jsonMenuData)
              }
            })
          }

        }
      })
    })
  },

  loadData: function () {

    const jsonDataUrls = {
      menu: "https://mm-mb-test.oss-cn-beijing.aliyuncs.com/menu.json?Expires=3294386888&OSSAccessKeyId=LTAI5tLaya38qPpXW3EVyMLq&Signature=TxhOVOmNvaAOKI2QFS2W88NoZdQ%3D",
      article: "https://mm-mb-test.oss-cn-beijing.aliyuncs.com/article.json?Expires=3294386888&OSSAccessKeyId=LTAI5tLaya38qPpXW3EVyMLq&Signature=OnlFuGphCC03uEk09HcBIlU0qtE%3D",
      articleContent: "https://mm-mb-test.oss-cn-beijing.aliyuncs.com/articleContent.json?Expires=3294386889&OSSAccessKeyId=LTAI5tLaya38qPpXW3EVyMLq&Signature=lBbLG8yOvDlxUsTkdJpnIeV7lE4%3D"

    }
    Promise.all([
      this.downloadAndParseJsonFile(jsonDataUrls.menu),
      this.downloadAndParseJsonFile(jsonDataUrls.article),
      this.downloadAndParseJsonFile(jsonDataUrls.articleContent)
    ]).then(([menu, article, articleContent]) => {
         // const outPutJsonData = this.processJsonData(menu.menu, article.article, articleContent.articleContent)
         this.jsonUsedData = this.processJsonData(menu.menu, article.article, articleContent.articleContent)
         console.log("outputMAhhh",this.jsonUsedData)
         // console.log("outputMA", menuArticleJsonData)
         
   
      wx.setStorageSync('menu', menu);
      wx.setStorageSync('article', article);
      wx.setStorageSync('articleContent', articleContent);
      wx.setStorageSync('jsonUsedData', this.jsonUsedData)
      this.setData({
        menu: menu,
        article: article,
        articleContent: articleContent
      });

      if (menu === null || article === null || articleContent === null) {
        this.setData({
          menu: wx.getStorageSync('menu'),
          article: wx.getStorageSync('article'),
          articleContent: wx.getStorageSync('articleContent'),
          jsonUsedData: wx.getStorageSync('jsonUsedData')
        })
      }
      // 存储到全局
      const app = getApp();
      app.globalData.menu = menu;
      app.globalData.article = article;
      app.globalData.articleContent = articleContent;
      app.globalData.jsonUsedData = this.jsonUsedData;
      console.log("ceshi ",app.globalData.jsonUsedData)
      
    })

  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadData();
    
    const app = getApp();
    this.setData({
      jsonUsedData:app.globalData.jsonUsedData
    })
    let length = this.data.jsonUsedData[4].article.length -1
    console.log("length",length)
    this.setData({
      contentIndex01:  app.towxml(this.data.jsonUsedData[4].article[length].content.content,'markdown')
    })
    // this.data.contentIndex01 = this.data.jsonUsedData[4].article[0].content.content
    console.log("index01 data",this.data.jsonUsedData)
    console.log("index01 data",this.data.contentIndex01)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // "余江概况"
    wx.setNavigationBarTitle({title:"余江概况"})

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})